import React, {PureComponent} from 'react';
import {
	Button,
	StyleSheet, Text, TextInput,
	View
} from 'react-native';

// npm i react-native-rsa
var RSAKey = require('react-native-rsa');
const bits = 1024;
const exponent = '10001';
var rsa = new RSAKey();
rsa.generate(bits, exponent);
var publicKey = rsa.getPublicString();
var privateKey = rsa.getPrivateString();
console.log("public: " + publicKey);
console.log("private: " + privateKey);


/**
 * @FileName: RsaRNDemo
 * @Author: mazaiting
 * @Date: 2018/7/2
 * @Description:
 */
class RsaRNDemo extends PureComponent {
	constructor(props) {
		super(props);
		this.state = {
			data: '',
			text: ''
		}
	}
	render() {
		return (
			<View style={styles.container}>
				<TextInput
					onChangeText={(text) => this.setState({data: text})}
				/>
				<Button
					title='加密'
					onPress={() => this.encrypt()}
				/>
				<Button
					title='解密'
					onPress={() => this.decrypt()}
				/>
				<Text>{this.state.text}</Text>
			</View>
		)
	}
	
	/**
	 * 加密
	 */
	encrypt() {
		let rsa = new RSAKey();
		// rsa.setPublicString(publicKey);
		rsa.setPrivateString(privateKey);
		let encrypted = rsa.encrypt(this.state.data);
		console.log(encrypted);
		this.setState({
			text: encrypted
		})
	}
	
	/**
	 * 解密
	 */
	decrypt() {
		let rsa = new RSAKey();
		// rsa.setPrivateString(privateKey);
		rsa.setPublicString(publicKey);
		let decrypted = rsa.decrypt(this.state.text);
		console.log(decrypted);
		this.setState({
			text: decrypted
		})
	}
}

/**
 * 样式属性
 */
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#DDD'
	}
});

/**
 * 导出当前Module
 */
module.exports = RsaRNDemo;